<template>
  <CDialog
    class="reduction-dialog"
    :title="title"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
    size="default"
  >
    <el-form ref="formRef" :model="taskForm" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工厂" prop="factoryName">
            <el-select
              v-model="taskForm.factoryName"
              placeholder="请选择"
              :suffix-icon="SelectIcon"
            >
              <el-option
                v-for="item in factoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目时间" prop="projectTime">
            <el-date-picker
              class="date-time__picker"
              v-model="taskForm.projectTime"
              type="datetime"
              placeholder="请选择"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
              :prefix-icon="DateTimeIcon"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <p class="g-font-14n1 g-mb4">项目减排量<span class="g-ml4 required-star">*</span></p>
      <el-row class="project-emission" :gutter="20">
        <el-col :span="12">
          <el-form-item label="CO₂" prop="coReduction" class="no-required-star">
            <el-input
              v-model="taskForm.coReduction"
              :min="0"
              :max="999999999"
              v-positive-only:6
              type="number"
              placeholder="请输入"
            >
              <template #suffix> t </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="SO₂" prop="soReduction" class="no-required-star">
            <el-input
              v-model="taskForm.soReduction"
              :min="0"
              :max="999999999"
              v-positive-only:6
              type="number"
              placeholder="请输入"
            >
              <template #suffix> t </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="N₂O"
            prop="noReduction"
            :min="0"
            :max="999999999"
            v-positive-only:6
            class="no-required-star"
          >
            <el-input v-model="taskForm.noReduction" type="number" placeholder="请输入">
              <template #suffix> t </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="VOCs"
            prop="vocsReduction"
            :min="0"
            :max="999999999"
            v-positive-only:6
            class="no-required-star"
          >
            <el-input v-model="taskForm.vocsReduction" type="number" placeholder="请输入">
              <template #suffix> t </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <p class="g-font-14n1 g-mt16 g-mb4">项目资料</p>
      <el-row>
        <el-col :span="24">
          <el-form-item label="" prop="file">
            <g-upload
              :file-size-limit="50"
              :limit="10"
              :action="uploadFilePostUrlV3"
              multiple
              :postParams="{
                groupType: 'BOOK_REDUCTION_PROJECT',
                scope: 'book',
                needRename: false
              }"
              v-model:fileList="taskForm.file"
              tip="支持上传多个文件"
            >
              <template #default="{ loading: btnLoading }">
                <el-button :loading="btnLoading"
                  ><CIcon type="c-xian-shangchuan" class="g-mr4"></CIcon>上传文件</el-button
                >
              </template>
            </g-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'ModifyDialog'
};
</script>
<script lang="ts" setup>
import {
  defineProps,
  withDefaults,
  defineEmits,
  computed,
  ref,
  watch,
  reactive,
  defineComponent,
  h
} from 'vue';
import { CDialog } from '@/components/CDialog';
import { useMessage } from '@/hooks/useMessage';
import { rules } from './rules';
import { AddOrEditFactoryParams } from '@/apis/taa/target/model/reductionModel';
import { addReduction, editReduction, getFactoryList } from '@/apis/taa/target/reduction';
import { GUpload } from '@/components/GUpload/index';
import { uploadFilePostUrlV3 } from '@/apis/common/common';
import { GIcon } from '@/components/GIcon/index';

// 下拉图标
const SelectIcon = defineComponent({
  setup() {
    return () => h(GIcon, { type: 'c-xian-xia', style: 'font-size: 16px' });
  }
});

// 时间图标
const DateTimeIcon = defineComponent({
  setup() {
    return () => h(GIcon, { type: 'c-xian-riqi', style: 'font-size: 14px' });
  }
});

interface SelectFillTypeDialogProps {
  visible: boolean;
  // 提交类型
  type: 'ADD' | 'EDIT';
  // 当前行数据，编辑时必传
  rowData: any;
}
const props = withDefaults(defineProps<SelectFillTypeDialogProps>(), {
  visible: false,
  type: 'ADD',
  rowData: {}
});
const emit = defineEmits(['update:visible', 'refresh']);

const { createMessage } = useMessage();

const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  visible => {
    if (!visible) {
      // 关闭时清空数据
      handleClear();
    } else {
      // 打开时初始化新数据
      initVisible();
    }
  }
);
const title = computed(() => {
  return props.type === 'EDIT' ? '编辑碳减排项目' : '新增碳减排项目';
});
const isEditTask = computed(() => {
  return !!(props.type === 'EDIT');
});

interface OptionItem {
  label: string;
  value: string;
}

const factoryOptions = ref<OptionItem[]>([]);
const formRef = ref();
const loading = ref(false);
const taskForm = reactive({
  factoryName: '',
  projectTime: '',
  coReduction: '',
  soReduction: '',
  noReduction: '',
  vocsReduction: '',
  file: []
});

async function getOptions() {
  try {
    const data = await getFactoryList();
    console.log(data, 'data');
    factoryOptions.value = data.map(item => {
      return {
        label: item,
        value: item
      };
    });
  } catch (error) {
    console.log(error, 'error');
  }
}

// 提交按钮
function handleConfirm() {
  console.log(taskForm.file, 'taskForm.file');
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      submitTaskReq();
    }
  });
}

// 请求接口
async function submitTaskReq() {
  try {
    loading.value = true;
    const params: AddOrEditFactoryParams = {
      factoryName: taskForm.factoryName,
      projectTime: taskForm.projectTime,
      coReduction: taskForm.coReduction,
      soReduction: taskForm.soReduction,
      noReduction: taskForm.noReduction,
      vocsReduction: taskForm.vocsReduction,
      file: taskForm.file.map((item: { name: string; url: string }) => {
        return {
          fileName: item.name,
          fileUrl: item.url
        };
      })
    };
    if (isEditTask.value) {
      Object.assign(params, {
        projectNo: props.rowData.projectNo
      });
      await editReduction(params);
    } else {
      await addReduction(params);
    }
    createMessage.success(`${isEditTask.value ? '编辑' : '新增'}供应商成功`);
    dialogVisible.value = false;
    loading.value = false;
    emit('refresh');
  } catch (error) {
    loading.value = false;
  }
}

// 关闭时清空数据
function handleClear() {
  loading.value = false;
  formRef.value?.resetFields();
  taskForm.factoryName = '';
  taskForm.projectTime = '';
  taskForm.coReduction = '';
  taskForm.soReduction = '';
  taskForm.noReduction = '';
  taskForm.vocsReduction = '';
  taskForm.file = [];
}

// 打开时初始化
async function initVisible() {
  // 获取工厂下拉选项
  getOptions();
  if (props.type === 'EDIT' && props.rowData.projectNo) {
    taskForm.factoryName = props.rowData.factoryName;
    taskForm.projectTime = props.rowData.projectTime;
    taskForm.coReduction = props.rowData.coReduction;
    taskForm.soReduction = props.rowData.soReduction;
    taskForm.noReduction = props.rowData.noReduction;
    taskForm.vocsReduction = props.rowData.vocsReduction;
    // taskForm.file = props.rowData.file;
    if (props.rowData.file) {
      taskForm.file = props.rowData.file.map((item: { fileName: string; fileUrl: string }) => {
        return {
          name: item.fileName,
          url: item.fileUrl
        };
      });
    } else {
      taskForm.file = [];
    }
  } else {
    handleClear();
  }
}
</script>
<style lang="scss" scoped>
.project-emission {
  background: #f3f7fb;
  padding: 12px 6px 0;
  border-radius: 3px;
  border: 1px solid #ebeff2;
  margin-left: unset !important;
  margin-right: unset !important;
}
.required-star {
  color: var(--el-color-danger);
  font-size: 14px;
  font-weight: 600;
}
.no-required-star {
  :deep(.el-form-item__label) {
    &::after {
      display: none;
    }
  }
}
</style>
<style lang="scss">
.reduction-dialog {
  .el-input {
    .el-input__wrapper {
      padding-right: 10px !important;
    }
  }

  .date-time__picker {
    .el-input__wrapper {
      .el-input__prefix {
        order: 3;
        .el-input__prefix-inner > :last-child {
          margin-right: unset;
        }
      }
    }
  }
}
</style>
